import os
import time
from urllib import response

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

from python_ty.gtly.slide_to_unlock import SlideToUnlockV1, SlideToUnlockFailed
import sys
import time
from io import BytesIO
from selenium.webdriver.common.proxy import Proxy, ProxyType
import cv2
import os
import requests
import random
import numpy as np
from PIL import Image as Im
from selenium import webdriver
from selenium.webdriver import ActionChains, Proxy
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

wait_time_short = 1
wait_time1_long = 2

class JdService:
    """

    jd service

    """


    LOGIN_URL: str = 'https://mag.96533.com:8243/personService/index.html#/login/UserLogin'

    def __init__(self):
        options = webdriver.ChromeOptions()
        options.add_experimental_option('detach', True)  # 不自动关闭浏览器
        # options.add_argument(
        #     '--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"')  # 设置请求头的User-Agent
        # options.add_argument('--incognito')  # 隐身模式（无痕模式）

        #options.add_argument("--proxy-server=https://221.11.233.111:4315")
        #options.add_argument('--headless') #不打开浏览器
        #options.add_argument('--start-maximized')  # 浏览器窗口最大化
        #self.driver = webdriver.Chrome(options=options)

        # proxy = '172.18.10.32:10001'
        # options.add_argument("–proxy-server=http://" + proxy)
        # options.add_argument('user-agent="%s"' % get_user_agent())
        self.driver = webdriver.Chrome(options=options)

        self.save_dir = sys.path[0] + "/pic/"

    def login(self):
        self.driver.get(self.LOGIN_URL)

        #点击密码登录
        self.driver.find_element(By.XPATH,'//*[@id="app"]/div[3]/div/div/div/div[1]/div[2]').click()
        # 输入 号码
        # phone_input_element_xpath = '//*[@id="el-id-7078-0"]'
        # self.driver.find_element(By.XPATH, phone_input_element_xpath).send_keys('*********')
        # time.sleep(1)
        #输入账户
        self.driver.find_element(By.XPATH,'//*[@id="app"]/div[3]/div/div/div/div[2]/div[2]/div/input').send_keys(18010525830)
        # 点击验证
        get_captcha_element_xpath = '//*[@id="app"]/div[3]/div/div/div/div[4]'
        self.driver.find_element(By.XPATH, get_captcha_element_xpath).click()
        time.sleep(1)



        self.verification_code(60)

        #输入密码
        self.driver.switch_to.default_content()
        self.driver.find_element(By.XPATH,'//*[@id="app"]/div[3]/div/div/div/div[3]/div/div/input').send_keys('xmgj1234566')

        #点击登录
        self.driver.find_element(By.CLASS_NAME,'loginBtn').click()
        # time.sleep(3)
        # #刚进来没有token得随便点下
        # self.driver.find_element(By.XPATH,'//*[@id="app"]/div[3]/div/div[2]/div[2]/div[5]/div[1]').click()
        # time.sleep(3)
        #
        # cookies = self.driver.get_cookies()
        # token = self.driver.execute_script('return localStorage.getItem("X-Access-Token");')
        # return cookies

    def verification_code(self, offset):
        self.driver.switch_to.default_content()
        self.driver.switch_to.frame('tcaptcha_iframe')

        #点了下重试
        # 点击刷新
        self.driver.find_element(By.XPATH, '//*[@id="reload"]/div').click()
        time.sleep(wait_time1_long)

        # 小的哪个缺口图片
        small_pic_pattern = 'slideBlock'
        small_url = self.driver.find_element(By.ID, small_pic_pattern).get_attribute('src')

        # print(small_url)
        #url("https://t.captcha.qq.com/cap_union_new_getcapbysig?img_index=0&image=02442700005fef3e0000000bb5d7a99e3988&sess=s0MyZoNAtLY2oBqoP886sYZ9lJ6f4Fk5S3pmzTgw7Dkgbo9-8T8c9Fe2TWyIKxzF8He5sAgef9oljHR3nGJRXUoxxR0lXE2rAAZ5vGqIu9-CUjqCiupd29e2emUR9mkm1ff-p2qeG66q4a5LUL8ZEBJBJHG-CfMRNFRMT71oveCCiz46Y7sIXQVSQCj3ZzalXFhLx7YebZurGoFqCl1_toIMw-bE8bNijkbQORIzEVmuIsoyTCmTaWSoL-c4nqDq_iAohOMa4CtY76HOuZ3QPcPMC_uxu3UfKZyA5DC9mV3AGFDYaRAOjU_2rvFhMRG2lJsCM1h6FgxXMYrCZ96SPmX_56VweA_0CfBaMtmUigZ3V2ReYgYjUPew**")
        # small_url = small_url.split('"')[1]
        print("small_url:", small_url)

        #大的背景图片
        big_pic_pattern = '/html/body/div/div[3]/div[2]/div[1]/div[2]/img'
        big_url = self.driver.find_element(By.XPATH, big_pic_pattern).get_attribute('src')
        #big_url = big_url.split('"')[1]
        print("big_url:",big_url)

        distance = self.get_distance(small_url, big_url)
        #distance = (distance - offset) * (280.0 / 680.0)
        distance = (distance - offset)
        print("distance:", distance)
        #下面的滑块非图片缺口
        element = self.driver.find_element(By.ID, 'tcaptcha_drag_thumb')
        ActionChains(self.driver).click_and_hold(element).perform()
        time.sleep(0.1)
        steps = self.get_steps(distance)
        print("steps:", steps)
        for step in steps:
            ActionChains(self.driver).move_by_offset(step, random.randint(-5, 5)).perform()
            # time.sleep((random.randint(5, 15) / 100000))

        ActionChains(self.driver).release(on_element=element).perform()
        time.sleep(wait_time1_long)
        try:
            self.driver.switch_to.default_content()
            self.driver.switch_to.frame('tcaptcha_iframe')
            print('滑动失败!')
            self.verification_code(60)
        except Exception as e:
            print('滑动成功')


    def download_img(self, url, size_type):
        try_times = 3
        #设置我要保存的图片的路径
        path = self.save_dir + size_type + '.png'
        while try_times > 0:
            try:
                if not os.path.exists(self.save_dir):
                    os.makedirs(self.save_dir)
                res = requests.get(url)
                if size_type == "small_needcrop":
                    img = Im.open(BytesIO(res.content))
                    # print('res.content = ',res.content)
                    # print('BytesIO(res.content) = ',BytesIO(res.content))
                    # print('img = ',img)
                    #剪切图片crop
                    crop = img.crop((140, 490, 260, 610))
                    #Image.crop(left, up, right, below)
                        #left：与左边界的距离

                        #up：与上边界的距离

                        #right：还是与左边界的距离

                        #below：还是与上边界的距离

                    #保存图片
                    crop.save(path)
                    return path
                else:
                    with open(path, "wb") as f:
                        f.write(res.content)
                    return f.name
            except Exception as e:
                print(e)
                try_times -= 1

    def get_distance(self, small_url, big_url):
        s_img = self.download_img(small_url, 'small')
        time.sleep(2)
        b_img = self.download_img(big_url, 'big')
        print("s_img:", s_img)
        print("b_img:", b_img)
        small_pic = cv2.Canny(cv2.GaussianBlur(cv2.imread('pic/small.png'), (5, 5), 0), 100, 300)
        big_pic = cv2.Canny(cv2.GaussianBlur(cv2.imread('pic/big.png'), (5, 5), 0), 100, 300)
        res = cv2.matchTemplate(big_pic, small_pic, cv2.TM_CCOEFF_NORMED)
        x, y = np.unravel_index(res.argmax(), res.shape)
        # min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        # print('max_loc[0]:', max_loc[0])
        return y


    def get_steps(self, dis):
        # 计算公式：v=v0+at, s=v0t+½at², v²-v0²=2as
        v = 0
        t = 0.3
        steps = []
        current = 0
        mid = dis / 2
        while current < dis:
            if current < mid:
                a = 2
            else:
                a = -2
            v0 = v
            s = v0 * t + 0.5 * a * (t ** 2)
            current += s
            steps.append(round(s))
            v = v0 + a * t
        return steps


if __name__ == '__main__':
    jd_service = JdService()
    jd_service.login()
